from marajo.appengine.handlers.db import DBHandler
from marajo.appengine.api.users import User
from marajo.exceptions import Unauthorized
from resources.project import Project
from resources.release import Release
from datetime import datetime


import logging
log = logging.getLogger("vermouth.release_handler")

class ReleaseHandler(DBHandler):
    """
    Add in extra permissions, and 
    add hooks for the UI to call this
    directly from a project page
    """

    def create_form(self):
        # Get a list of the properties to display here
        properties = self.db_class.properties()
        d = {'properties' : properties,
             'action_method' : 'POST',
             'action_label' : 'Create',
             'action_href' : self.request.script_name}
        if self.request.GET.getone("project"):
            d['project'] = Project.get_by_ids(self.request.GET.getone("project"))
        d['obj'] = Release()
        self.display(self.create_template, d)

    def update(self, obj, props):
        """
        Hook in to set the date_finished when the status is set 
        to "finished"
        We also make sure this user is an employee, and assigned to this project
 or self.user.has_auth_group("admin"):
        """
        if not obj.project:
            obj.project = Project.get_by_ids(self.request.POST.getone("project"))
        if self.user.has_auth_group("admin") or (self.user.has_auth_group("employee") and self.user in obj.project.members):
            if obj.status != "finished" and props.get("status", None) == "finished":
                obj.date_finished = datetime.now()
            return DBHandler.update(self, obj, props)
        else:
            raise Unauthorized()
